package com.example.lotterysystem.service.mq;

import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.controller.param.DrawPrizeParam;
import com.example.lotterysystem.dao.dataobject.ErrorMessageDO;
import com.example.lotterysystem.dao.mapper.ErrorMessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.example.lotterysystem.common.config.DirectRabbitConfig.*;
import static com.example.lotterysystem.service.DrawPrizeService.MESSAGE_DATA;
import static com.example.lotterysystem.service.DrawPrizeService.MESSAGE_ID;

@Component
@RabbitListener(queues = DLX_QUEUE_NAME)
@Slf4j
public class DlxReceiver {
    @Autowired
    private ErrorMessageMapper errorMessageMapper;

    @RabbitHandler
    public void process(Map<String, String> message) {
        // 日志打印
        String paramString = message.get(MESSAGE_DATA);
        log.info("异常消息: {}", paramString);
        // 获取请求参数
        DrawPrizeParam drawPrizeParam = JacksonUtil.readValue(paramString, DrawPrizeParam.class);
        // 对异常消息进行处理(将异常消息存储至数据表中)
        // 构造 dao 层请求
        List<ErrorMessageDO> errorMessageDOList = drawPrizeParam.getWinnerList()
                .stream()
                .map(winner -> {
                    ErrorMessageDO errorMessageDO = new ErrorMessageDO();
                    errorMessageDO.setMessageId(message.get(MESSAGE_ID));
                    errorMessageDO.setActivityId(drawPrizeParam.getActivityId());
                    errorMessageDO.setPrizeId(drawPrizeParam.getPrizeId());
                    errorMessageDO.setWinnerId(winner.getUserId());
                    errorMessageDO.setWinnerName(winner.getUserName());
                    errorMessageDO.setWinningTime(drawPrizeParam.getWinningTime());
                    return errorMessageDO;
                }).collect(Collectors.toList());
        // 存储
        errorMessageMapper.batchInsert(errorMessageDOList);
    }
}
